<template>
  <div>
    <h2>设置</h2>
    <el-tabs>
      <el-tab-pane label="SQL">
        <el-scrollbar>
          <sql-page :column-headers="columnHeaders" />
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import type { SqlBuilderSettings } from "./components/sql/types";
import { sqlBuilderSettings } from "./store";
import type { ServiceType, Transmission } from "./types";

const columnHeaders = ref("");

function getSettingData(service: ServiceType): unknown {
  switch (service) {
    case "sql-builder": {
      return sqlBuilderSettings.value;
    }
  }
}

function setSettingData(service: ServiceType, data: unknown) {
  switch (service) {
    case "sql-builder": {
      const sqlSettings = data as SqlBuilderSettings;
      if (sqlSettings) {
        sqlBuilderSettings.value = sqlSettings;
      }
      break;
    }
  }
}

function post(transmission: Transmission) {
  window.chrome?.webview?.postMessage(transmission);
}

function loadColumnHeaders() {
  post({ command: "get-column-headers", service: "global" });
}

// 挂载WebView回调
window.chrome?.webview?.addEventListener("message", (event) => {
  const trans = event.data as Transmission;
  if (!trans) {
    return;
  }

  switch (trans.command) {
    // 获取当前的设置文件，忽略后端请求传递 data 属性
    case "get-setting-data": {
      post({
        command: "get-setting-data",
        service: trans.service,
        data: getSettingData(trans.service),
      });
      break;
    }
    // 设置当前的设置文件
    case "set-setting-data": {
      setSettingData(trans.service, trans.data);
      break;
    }
    // 设置列头
    case "set-column-headers": {
      const headers = trans.data as string;
      if (headers) {
        columnHeaders.value = headers;
      }
      break;
    }
  }
});

// 启动时，
onMounted(() => {
  loadColumnHeaders();
});
</script>

<style lang="css">
.el-tabs__item {
  min-width: 60px;
  align-items: center;
}
</style>
